package com.example.securitymy.domain;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@AllArgsConstructor
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    public LoginUser(User user) {
        this.user = user;
    }
    private User user; // 确保构造时已传入有效User对象
   // 存储权限信息
    private List<String> permissions;

    public LoginUser(User user, ArrayList<String> list) {
        this.user = user;
        this.permissions = list;
    }

    // ====== 核心凭证方法 ======
    @Override
    public String getUsername() {
        return user != null ? user.getUserName() : null;
    }

    @Override
    public String getPassword() {
        return user != null ? user.getPassword() : null;
    }

    // ====== 账户状态控制 ======
    @Override
    public boolean isEnabled() {
        // delFlag=0表示未删除
        return user != null && user.getDelFlag() != null && user.getDelFlag() == 0;
    }

    @Override
    public boolean isAccountNonLocked() {
        // status=0表示账号正常
        return user != null && user.getStatus() != null && "0".equals(user.getStatus());
    }

    // ====== 其他状态（根据业务需求调整） ======
    @Override
    public boolean isAccountNonExpired() {
        return true; // 账户未过期（如需实现过期逻辑需添加字段）
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true; // 凭证未过期
    }
    // 存储权限
    // TODO:修改FastJson为Jackson,使用FastJson序列化如果不加入下面的注解会报错
    @JSONField(serialize = false) //忽略
    private List<SimpleGrantedAuthority> authorities;

    // ====== 权限配置 ======
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
       if(authorities != null){
           return authorities;
       }else {
           ////把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities
           authorities = permissions.stream()
                   .map(SimpleGrantedAuthority::new)
                   .collect(Collectors.toList());
           return authorities;
       }
    }
}
